from __future__ import division
from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404
from django.http import HttpResponseRedirect, HttpResponse
from django.core.serializers.json import DjangoJSONEncoder
from django.template import RequestContext
from CourseHub.form import RegisterForm, CreateCourseForm, CreateCommentForm, SearchForm
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from models import Course, School, Comment
from datetime import datetime
from django.utils import simplejson
from django.core import serializers
from decimal import Decimal


def Register(request):
    if request.POST:
        form = RegisterForm(request.POST)
        if form.is_valid():         
            form = form.save()
            return HttpResponseRedirect('/redirect/')
    else:
        form = RegisterForm()
    return render_to_response('register.html', RequestContext(request, {'form': form}))

@login_required
def CreateCourse(request):
    if request.POST:
        form = CreateCourseForm(request.user,request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/course/')
    else:
        form = CreateCourseForm(request.user)
    return render_to_response('CreateCourse.html', RequestContext(request, {'form': form}))

def PopularCourse(request):
    CourseList = Course.objects.order_by('-course_average')[:10]
    return render_to_response('CourseIndex.html', RequestContext(request, {'CourseList': CourseList}))

def LatestComment(request):
    CommentList  = Comment.objects.order_by('-comment_date')[:10]
    return render_to_response('LatestComment.html', {'CommentList': CommentList}, context_instance=RequestContext(request))

def CreateComment(request):
    if request.POST:
        form = CreateCommentForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/course/')
    else:
        form = CreateCommentForm()
    return render_to_response('CreateComment.html', RequestContext(request, {'form': form}))

def CourseDetail(request, course_id):
    # Get course object and list of comment object
    CourseDetail = get_object_or_404(Course, pk=course_id)
    CommentList = list(Comment.objects.filter(course=CourseDetail))
    
    if request.user.is_authenticated():
        if request.POST:
            form = CreateCommentForm(CourseDetail,request.POST)
            if form.is_valid():
                form.save()
                comment_date  = datetime.now()
                course_json = {
                'comment_year': form.cleaned_data['comment_year'],
                'comment_semester': form.cleaned_data['comment_semester'], 
                'comment_title': form.cleaned_data['comment_title'],
                'comment_tutor': form.cleaned_data['comment_tutor'], 
                'comment_rating': form.cleaned_data['comment_rating'], 
                'comment_text': form.cleaned_data['comment_text'], 
                'comment_date': comment_date}

                # Calculate Average Rating
                averageRating = 0.0
                accRating = 0.0
                comListLen = 0
                new_CommentIndex = list(Comment.objects.filter(course=CourseDetail))
                for comment in new_CommentIndex:
                    accRating += comment.comment_rating
                    comListLen += 1
                    print comListLen
                averageRating = accRating / comListLen
                
                print averageRating
                
                # Update Course record
                CourseDetail.course_average = averageRating
                CourseDetail.course_date = datetime.now()
                CourseDetail.save(force_update=True)

                return HttpResponse(simplejson.dumps(course_json, cls=DjangoJSONEncoder), mimetype='application/json')
        else:
            form = CreateCommentForm(CourseDetail)
        return render_to_response('CourseDetail.html', RequestContext(request, {'CourseDetail': CourseDetail, 'CommentList': CommentList, 'form': form}))
    else:
        return render_to_response('CourseDetail.html', {'CourseDetail': CourseDetail, 'CommentList': CommentList}, context_instance=RequestContext(request))

def AdvanceSearch(request):
    CourseList = None
    if request.POST:
        form = SearchForm(request.POST)
        if form.is_valid():
            university = form.cleaned_data['university']
            course_title = form.cleaned_data['course_title']
            course_code = form.cleaned_data['course_code']
            course_subject = form.cleaned_data['course_subject']

            if course_title != None:
                CourseList = Course.objects.filter(course_title__contains = course_title)
            else:
                CourseList = Course.objects.all()
            if course_subject != None:
                CourseList = CourseList.filter(course_subject__contains = course_subject)
            if university != None:
                CourseList = CourseList.filter(school = School.objects.filter(university = university))
            if course_code != None:
                CourseList = CourseList.filter(course_code__contains = course_code)
    else:
        form = SearchForm()
    return render_to_response('Search.html', RequestContext(request, {'CourseList': CourseList, 'form': form}))